import java.util.Stack;

/**
 * 20 有效的括号
 *
 * @author suncp
 * @date 2020/12/29 9:36
 */
public class IsBrackets {
    public static void main(String[] args) {
//        注意空字符串可被认为是有效字符串
//        String ts = "";
//        String ts = "()";
//        String ts = "(]";
        String ts = "{[]}";
//        String ts = "()[]{}";
        boolean valid = isValid(ts);
        System.out.println("返回判断结果： " + valid);
    }

    private static boolean isValid2(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
            if (c == '(') stack.push(')');
            else if (c == '[') stack.push(']');
            else if (c == '{') stack.push('}');
            else if (stack.isEmpty() || c != stack.pop()) return false;
        }
        return stack.isEmpty();
    }

    private static boolean isValid(String s) {
        if (s == null) return false;
        int len = s.length();
        char[] stack = new char[len];
        int index = -1;
        for (char c : s.toCharArray()) {
            if (c == '(') stack[++index] = ')';
            else if (c == '[') stack[++index] = ']';
            else if (c == '{') stack[++index] = '}';
            else if (index == -1 || stack[index--] != c) return false;
        }
        return index == -1;
    }
}
